﻿using DAO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace BALayer
{
    public class UserBA
    {
        public static UserDAO checkUser(string userName, string passWord)
        {
            UserDAO userLogin = new UserDAO();
            StringBuilder sql = new StringBuilder();
            DataTable dt = new DataTable();

            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            UnicodeEncoding encoding = new UnicodeEncoding();
            Byte[] hashBytes = encoding.GetBytes(passWord);
            Byte[] cryptBytes = sha1.ComputeHash(hashBytes);

            sql.Append("SELECT * FROM A ");
            sql.Append(" where UserName = @UserName ");
            sql.Append(" and MatKhau = @PassWord");
            try
            {
                dt = DataAccess.Access.ExcuQuery(sql.ToString(),
                                new OleDbParameter("UserName", userName),
                                new OleDbParameter("PassWord", BitConverter.ToString(cryptBytes)));
                if (dt.Rows.Count < 1)
                {
                    return null;
                }
                userLogin.Id = Int32.Parse(dt.Rows[0].ItemArray[0].ToString());
                userLogin.UserName = dt.Rows[0].ItemArray[1].ToString();
                userLogin.PassWord = dt.Rows[0].ItemArray[2].ToString();
                return userLogin;
            }
            catch (Exception)
            {
                throw new Exception("Không tồn tại database!");
            }
            
        }
        public static int changePassWord(UserDAO user)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("update A set ");
            sql.Append(" MatKhau = @PassWord ");
            sql.Append(" where ID = @ID");
            try
            {
                return DataAccess.Access.ExcuNonQuery(sql.ToString(),
                                new OleDbParameter("@PassWord", user.PassWord),
                                new OleDbParameter("@ID", user.Id));
            }
            catch (Exception)
            {
                throw new Exception("Không thể thay đổi mật khẩu");
            }
            
        }
    }
}
